package com.yds.developtools.views;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.yds.developtools.R;
import com.yds.developtools.views.adapter.CommonViewHolder;
import com.yds.developtools.views.adapter.YDSRecyclerViewOAdapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 创建者：于德水
 * 创建时间：2021/9/24 0024 14:40
 * 创建描述：自定义选择时间段
 */
@SuppressWarnings("all")
public class YDSDateSelectDialog extends Dialog {

    private OnSelectDateListener mOnSelectDateListener;
    private boolean isSingle = false;

    private TextView tv_calendar_current_day, bt_calendar_confirm, bt_calendar_cancle;
    private ImageView iv_calendar_left, iv_calendar_right;
    private RecyclerView recyclerview_calendar;
    private int year, currentYear;
    private int month, currentMonth;
    private int day;
    private int emptyDayNum;           //补齐对应天数数量
    private int selectDayNum;          //已选择天数数量
    private YDSRecyclerViewOAdapter mCalendarAdapter;
    private List<String> mCalendarList;
    private Map<String, Boolean> mSeledtDayMap;
    private List<Long> selectDayList;
    private int currentPosition = 0;
    private Map<Integer, Boolean> rgMap = new HashMap<>();
    private String start = "";
    private String end = "";

    public YDSDateSelectDialog(@NonNull Context context) {
        this(context, R.style.normal_dialog);
    }

    public YDSDateSelectDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View updateIconView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_custom_select_date, null);
        initView(updateIconView);

        Window window = getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        window.setWindowAnimations(R.style.AnimBottom);
        window.setGravity(Gravity.CENTER);
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        window.setLayout((int) (displayMetrics.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(updateIconView);
    }

    public void setSelectDayType(boolean isSingle) {
        this.isSingle = isSingle;
    }

    public interface OnSelectDateListener {
        void selectDate(String startDate, String endDate);
    }

    public void setOnSelectDateListener(OnSelectDateListener listener) {
        mOnSelectDateListener = listener;
    }

    private void initView(View inflate) {
        tv_calendar_current_day = inflate.findViewById(R.id.tv_calendar_current_day);
        iv_calendar_left = inflate.findViewById(R.id.iv_calendar_left);
        iv_calendar_right = inflate.findViewById(R.id.iv_calendar_right);
        recyclerview_calendar = inflate.findViewById(R.id.recyclerview_calendar);
        bt_calendar_confirm = inflate.findViewById(R.id.bt_calendar_confirm);
        bt_calendar_cancle = inflate.findViewById(R.id.bt_calendar_cancle);

        mCalendarList = new ArrayList<>();
        mSeledtDayMap = new HashMap<>();
        emptyDayNum = 0;           //补齐对应天数数量
        selectDayNum = 0;       //已选择天数数量
        selectDayList = new ArrayList<>();

        Calendar mCalendar = Calendar.getInstance();
        year = mCalendar.get(mCalendar.YEAR);
        currentYear = mCalendar.get(mCalendar.YEAR);
        month = mCalendar.get(mCalendar.MONTH) + 1;
        currentMonth = mCalendar.get(mCalendar.MONTH) + 1;
        day = mCalendar.get(mCalendar.DAY_OF_MONTH);
        tv_calendar_current_day.setText(year + "年" + month + "月");

        initCalendarRecyclerview();
        initCalendarData();

        iv_calendar_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                month--;
                if (month == 0) {
                    month = 12;
                    year--;
                }
                initCalendarData();
            }
        });
        iv_calendar_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                month++;
                if (month == 13) {
                    month = 1;
                    year++;
                }
                initCalendarData();
            }
        });
        bt_calendar_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSingle) {
                    if (!selectDayList.isEmpty()) {
                        start = stampToDate(selectDayList.get(0));
                    } else {
                        start = year + "-" + month + "-" + day;
                    }
                    if (null != mOnSelectDateListener) {
                        mOnSelectDateListener.selectDate(start, end);
                    }
                    dismiss();
                } else {
                    Log.i("YDSimon","aaaaaaa123"+selectDayList.get(0));
                    if (selectDayList.size() == 2) {
                        if (!selectDayList.isEmpty()) {
                            Log.i("YDSimon","aaaaaaa"+selectDayList.get(0));
                            Log.i("YDSimon","bbbbbbb"+selectDayList.get(1));
                            start = stampToDate(selectDayList.get(0));
                            end = stampToDate(selectDayList.get(1));
                        }
                        if (null != mOnSelectDateListener) {
                            mOnSelectDateListener.selectDate(start, end);
                        }
                        dismiss();
                    } else {
                        Toast.makeText(getContext(), "请选择自定义时间段", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        bt_calendar_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != mOnSelectDateListener) {
                    mOnSelectDateListener.selectDate("", "");
                }
                dismiss();
            }
        });
    }

    /**
     * 日期列表
     */
    private void initCalendarRecyclerview() {
        GridLayoutManager glm = new GridLayoutManager(getContext(), 7);
        recyclerview_calendar.setLayoutManager(glm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        recyclerview_calendar.setHasFixedSize(true);
        recyclerview_calendar.setNestedScrollingEnabled(false);

        mCalendarAdapter = new YDSRecyclerViewOAdapter(getContext(), R.layout.layout_calendar_item, mCalendarList);
        mCalendarAdapter.setItemDatasListener(new YDSRecyclerViewOAdapter.ItemDatasListener<String>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, String dataBean, final int position) {
                TextView tv_calendar_item = holder.getView(R.id.tv_calendar_item);
                View v_calendar_select_day_left = holder.getView(R.id.v_calendar_select_day_left);
                View v_calendar_select_day_right = holder.getView(R.id.v_calendar_select_day_right);

                v_calendar_select_day_left.setVisibility(View.INVISIBLE);
                v_calendar_select_day_right.setVisibility(View.INVISIBLE);
                tv_calendar_item.setBackgroundResource(R.drawable.rect_calendar_item_bg);
                tv_calendar_item.setText(dataBean);

                final String dayItem = year + "-" + month + "-" + (dataBean.isEmpty() ? "" : ((Integer.parseInt(dataBean) < 10) ? ("0" + dataBean) : dataBean));
                //默认展示当天
                if (selectDayNum == 0) {
                    if (currentYear == year && currentMonth == month) {
                        if (dataBean.equals(day + "")) {
                            tv_calendar_item.setSelected(true);
                        } else {
                            tv_calendar_item.setSelected(false);
                        }
                    } else {//非当前年月的今天不展示
                        tv_calendar_item.setSelected(false);
                    }
                } else {//展示已选择day
                    tv_calendar_item.setSelected(mSeledtDayMap.get(dayItem));
                }

                //如果选择两天 贯穿之间所有day
                if (selectDayNum == 2) {
                    if (!TextUtils.isEmpty(dataBean)) {
                        Long start = selectDayList.get(0);
                        Long end = selectDayList.get(1);
                        if (dateToStamp(dayItem) == start) {
                            v_calendar_select_day_left.setVisibility(View.INVISIBLE);
                            v_calendar_select_day_right.setVisibility(View.VISIBLE);
                        } else if (dateToStamp(dayItem) == end) {
                            v_calendar_select_day_left.setVisibility(View.VISIBLE);
                            v_calendar_select_day_right.setVisibility(View.INVISIBLE);
                        } else if (dateToStamp(dayItem) > start && dateToStamp(dayItem) < end) {
                            v_calendar_select_day_left.setVisibility(View.VISIBLE);
                            v_calendar_select_day_right.setVisibility(View.VISIBLE);
                            tv_calendar_item.setBackgroundColor(getContext().getResources().getColor(R.color.red_FFF1F1));
                        } else {
                            v_calendar_select_day_left.setVisibility(View.INVISIBLE);
                            v_calendar_select_day_right.setVisibility(View.INVISIBLE);
                            tv_calendar_item.setBackgroundResource(R.drawable.rect_calendar_item_bg);
                        }
                    }
                }

                tv_calendar_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (dataBean.isEmpty())
                            return;

                        if (isSingle) {
                            if (selectDayNum >= 1) {
                                if (!selectDayList.contains(dateToStamp(dayItem))) {
                                    mSeledtDayMap.put(stampToDate(selectDayList.get(0)), false);
                                }
                            }
                        } else {
                            if (selectDayNum >= 2) {
                                if (!selectDayList.contains(dateToStamp(dayItem))) {
                                    mSeledtDayMap.put(stampToDate(selectDayList.get(1)), false);
                                }
                            }
                        }

                        //day反向选择
                        mSeledtDayMap.put(dayItem, !mSeledtDayMap.get(dayItem));
                        mCalendarAdapter.notifyDataSetChanged();

                        //计算day选择数量
                        Iterator<Map.Entry<String, Boolean>> iterator = mSeledtDayMap.entrySet().iterator();
                        selectDayNum = 0;
                        selectDayList.clear();
                        while (iterator.hasNext()) {
                            Map.Entry<String, Boolean> entry = iterator.next();
                            if (entry.getValue()) {
                                selectDayList.add(dateToStamp(entry.getKey()));
                                selectDayNum++;
                            }
                        }
                        if (!selectDayList.isEmpty()) {
                            Collections.sort(selectDayList);
                        }
                    }
                });
            }
        });

        mCalendarAdapter.setOnItemClickListener(new YDSRecyclerViewOAdapter.OnItemClickListener() {

            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {
            }
        });

        mCalendarAdapter.setHasStableIds(true);
        recyclerview_calendar.setAdapter(mCalendarAdapter);
    }

    /**
     * 计算当前月天数
     */
    private void initCalendarData() {
        mCalendarList.clear();
        String date = year + "-" + month + "-1";
        tv_calendar_current_day.setText(year + "年" + month + "月");
        int dayofWeek = getDayofWeek(date);
        //补全天数
        if (dayofWeek > 1) {
            for (int i = 0; i < dayofWeek - 1; i++) {
                mCalendarList.add("");
                if (!mSeledtDayMap.containsKey(year + "-" + month + "-")) {
                    mSeledtDayMap.put(year + "-" + month + "-", false);
                }
            }
        }
        emptyDayNum = mCalendarList.size();
        //当月天数
        int monthDays = getMonthDays(year, month);
        for (int i = 1; i <= monthDays; i++) {
            mCalendarList.add(i + "");
            if (!mSeledtDayMap.containsKey(year + "-" + month + "-" + ((i < 10) ? ("0" + i) : (i + "")))) {
                mSeledtDayMap.put(year + "-" + month + "-" + ((i < 10) ? ("0" + i) : (i + "")), false);
            }
        }

        mCalendarAdapter.notifyDataSetChanged();
    }

    /**
     * 得到指定月的天数
     */
    private int getMonthDays(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 获取当前day是星期几
     *
     * @return
     */
    private int getDayofWeek(String dateTime) {
        Calendar cal = Calendar.getInstance();
        if (dateTime.equals("")) {
            cal.setTime(new Date(System.currentTimeMillis()));
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            Date date;
            try {
                date = sdf.parse(dateTime);
            } catch (ParseException e) {
                date = null;
                e.printStackTrace();
            }
            if (date != null) {
                cal.setTime(new Date(date.getTime()));
            }
        }
        return cal.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 将时间转换为时间戳
     */
    public long dateToStamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return ts;
    }

    /**
     * 将时间戳转换为时间
     */
    public String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }

}
